# -*- coding: utf-8 -*-

import zlib
import sys
import os
import pythoncom
import struct
from win32com.shell import shell
from win32com import storagecon

one = 0
two = 4
sectionLen = 0
def zlib_raw_encode(input):
    output = zlib.compress(input)[2:-4]
    return output

def zlib_raw_decode(input):
    output = zlib.decompress(input, -15)
    return output

def getSubStorage(stg,filename):
    #print filename
    x_stg  = stg.OpenStorage(filename, None, 0x10,None,0)
    return x_stg

flags = storagecon.STGM_READ | storagecon.STGM_SHARE_EXCLUSIVE
def readOLE(stg,path):
    print "Path - %s" % path
    if not os.path.isdir("." + path + "/"):
        print "makedir !!"
        os.mkdir("." + path + "/")
                
    estat = stg.EnumElements();
    #print estat  
    str = estat.Next()

    while str != ():
        #print str
        len = str[0][2]

        # Storage
        if ( str[0][1] == 1 ):
            print "%s Size is %s" % (str[0][0] , "(storage)")
            x_stg = getSubStorage(stg,str[0][0])
            readOLE(x_stg,path+"/"+str[0][0])

        # properties
        elif ( str[0][0].find('\x05') >= 0 ) :
            print "  %s Size is %d %s" % (str[0][0] , len, "(properties)")
            if not os.path.isdir("." + path + "/"):
                print "makedir !!"
                os.mkdir("." + path + "/")
            f = open("." + path + "/"+str[0][0][1:], 'wb')
            f.write(data)
            f.close()
            
        # Stream
        else:
            print "  %s Size is %d %s" % (str[0][0] , len, "(stream)")
            ostream = stg.OpenStream(str[0][0], None, flags)
            data = ostream.Read(len)
            print "file create %s %s" % (path,str[0][0])
            print "." + path + "/"
            if not os.path.isdir("." + path + "/"):
                print "makedir !!"
                os.mkdir("." + path + "/")
            f = open("." + path + "/"+str[0][0], 'wb')
            if (str[0][0].find("Section0")  >= 0 ):
                data = zlib_raw_decode(data)
                f.write(data)
                f.close()
                global sectionLen
                sectionLen = os.path.getsize("." + path + "/"+str[0][0])
                print sectionLen
            else:
                f.write(data)
                f.close()
    
        str = estat.Next()



def search(stg,dirname):
    flist = os.listdir(dirname)
    for f in flist:
        next = os.path.join(dirname, f)
        if os.path.isdir(next):
            #print f
            newStg = stg.CreateStorage(f,0x12,0,0)
            newStg.Commit(1)
            search(newStg,next)
        else:
            #print "tt "+f
            if( f == "HwpSummaryInformation"):
                f = '\x05'+f
            oStream = stg.CreateStream(f,0x12,0,0)
            fp = open(next,"rb")
            if (f.find("Section0") >= 0):
                data = fp.read()
                #print "test %d %d" % (one,two)
                firstdata = data[:one]
                firstdata = firstdata + struct.pack('<I', 0xcccccccc)
                nextdata = data[two:]
                firstdata = firstdata + nextdata
                data = firstdata

                data = zlib_raw_encode(data)
                oStream.write(data)
                oStream.Commit(1)
                fp.close()

            else:
                oStream.write(fp.read())
                oStream.Commit(1)
                fp.close()
            #print next
            #doFileWork(stg,next)

def doFileWork(stg,filename):
    ext = os.path.splitext(filename)[-1]
#    print filename

   
    
def makeOLE(stg,path):
    search(stg,path)
    


print "####################################################"
filename = "testcase3.hwp"
print filename

if pythoncom.StgIsStorageFile(filename):
    stg = pythoncom.StgOpenStorage(filename, None, storagecon.STGM_READ | storagecon.STGM_SHARE_DENY_WRITE,None,0)
        
s = os.path.splitext(filename)
print s[0]
readOLE(stg,"/"+s[0])        

print sectionLen
print "####################################################"
print "File Maker"
for i in range(0,sectionLen):
    #print "####################################################"
    #print i
    testfilename = "make"
    testfilename = testfilename+'_'+str(i)+".hwp"
    if os.path.exists(testfilename):
        print "file exists, Delete!!"
        os.remove(testfilename)
    cstg = pythoncom.StgCreateDocfile(testfilename,0x12,0)
    #print "./"+s[0]
    makeOLE(cstg,"./"+s[0])
    one = one+1;
    two = two+1;

print sectionLen
print "Success"






#####################################################
##Compress -> Decompress
#####################################################
'''
CompressSectionFile = open('shell_Section0', 'rb')
FileBuf = CompressSectionFile.read()
#FileBuf = FileBuf[(3235+926+1+106+518+633+369+134+144+137+1+3+40+99+1+122+2+33+565+42+1+2+5+473+i):]
#FileBuf = FileBuf[:i]
CompressSectionFile.close()

decompressed = zlib_raw_decode(FileBuf)

DecompressFile = open('decompress_Section1','wb')
DecompressFile.write(decompressed)
DecompressFile.close()

#####################################################
##Decompress -> Compress
#####################################################

DecompressFile = open('final_decompress','rb')
FileBuf = DecompressFile.read()
DecompressFile.close()

compressed = zlib_raw_encode(FileBuf)

CompressFile = open('compress_Section0','wb')
CompressFile.write(compressed)
CompressFile.close()


#####################################################
##Compress -> Decompress
#####################################################
CompressSectionFile = open('compress_Section0', 'rb')
FileBuf = CompressSectionFile.read()
CompressSectionFile.close()
#print fileBuf

decompressed = zlib_raw_decode(FileBuf)

DecompressFile = open('de_decompress_Section0','wb')
DecompressFile.write(decompressed)
DecompressFile.close()

print "Complete"
'''

